package com.owen.controller;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.IoUtil;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.alibaba.fastjson2.JSON;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.owen.pojo.Vegetables;
import com.owen.server.VegetablesServer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Controller
@RequestMapping(value = "/vegetables")
public class VegetablesController {

    @Autowired
    private VegetablesServer vegetablesServer;

    @ResponseBody
    @RequestMapping(value = "/findAll")
    public String findAll() {

        PageHelper.startPage(1, 10);
        List<Vegetables> vegetables = vegetablesServer.findAll();
        PageInfo<Vegetables> vegetableInfo = new PageInfo<>(vegetables);

        Map<String, Object> res = new HashMap<>();
        if (vegetables != null) {
            res.put("code", "200");
            res.put("msg", "查询成功");
            res.put("data", vegetableInfo);
        } else {
            res.put("code", "201");
            res.put("msg", "查询失败");
        }
        String s = JSON.toJSONString(res);
        return s;
    }

    @ResponseBody
    @RequestMapping(value = "/findById/{id}")
    public String findById(@PathVariable("id") Integer id) {
        Vegetables vegetables = vegetablesServer.findById(id);
        Map<String, Object> res = new HashMap<>();
        if (vegetables != null) {
            res.put("code", "200");
            res.put("msg", "查询成功");
            res.put("data", vegetables);
        } else {
            res.put("code", "201");
            res.put("msg", "查询失败");
        }
        String s = JSON.toJSONString(res);
        return s;
    }

    @ResponseBody
    @RequestMapping(value = "/deleteBatch", method = RequestMethod.POST)
    public String deleteBatch(Integer[] ids) {
        Map<String, Object> res = new HashMap<>();
        Integer count = vegetablesServer.deleteBatch(ids);
        if (count > 0) {
            res.put("code", 200);
            res.put("msg", "删除成功！");
        } else {
            res.put("code", 201);
            res.put("msg", "删除失败！");
        }
        String json = JSON.toJSONString(res);
        return json;
    }

    @ResponseBody
    @RequestMapping(value = "/fileExport")
    public void fileExport(Vegetables vegetables, HttpServletResponse response) throws ClassNotFoundException, IndexOutOfBoundsException, IOException {
        // 生成excel
        ExcelWriter writer = ExcelUtil.getWriter();
        // 数据库查询
        List<Vegetables> vegetabless = vegetablesServer.findByVe(vegetables);
        List<Map<String, Object>> rows = vegetabless.stream().map(item -> {
            Map<String, Object> maps = new HashMap<>();
            maps.put("id", item.getId() == null ? "" : item.getId().toString());
            maps.put("createTime", item.getCreateTime());
            maps.put("name", item.getName());
            maps.put("address", item.getAddress());
            maps.put("addressPhoto", item.getAddressPhoto());
            maps.put("details", item.getDetails());
            return maps;
        }).collect(Collectors.toList());

        // Title
        int columns = Class.forName("com.owen.pojo.Vegetables").getDeclaredFields().length;
        writer.merge(columns - 1, "蔬菜信息");
        // Header
        writer.addHeaderAlias("id", "主键ID");
        writer.addHeaderAlias("createTime", "生产日期");
        writer.addHeaderAlias("name", "菜名");
        writer.addHeaderAlias("address", "产地");
        writer.addHeaderAlias("addressPhoto", "蔬菜照片");
        writer.addHeaderAlias("details", "详情");
        // Body
        writer.setColumnWidth(0, 30);
        writer.setColumnWidth(1, 30);
        writer.setColumnWidth(2, 30);
        writer.setColumnWidth(3, 30);
        writer.setColumnWidth(4, 30);
        writer.setColumnWidth(5, 30);
        writer.write(rows, true);
        response.setContentType("application/vnd.ms-excel;charset=utf-8");
        response.setHeader("Content-disposition", "attachment; filename=" + URLEncoder.encode("蔬菜信息-" + DateUtil.today() + ".xls", "utf-8"));
        ServletOutputStream out = response.getOutputStream();
        writer.flush(out, true);
        writer.close();
        IoUtil.close(out);
    }

    @ResponseBody
    @RequestMapping(value = "/findByVegetables")
    public String findByVegetables(Vegetables vegetables, Integer xuanzhepage, String currentPage) {

        // 获取页数
        Integer current = 1;
        if (currentPage != null) {
            current = Integer.valueOf(currentPage);
        }

        PageHelper.startPage(current, xuanzhepage);
        List<Vegetables> byVe = vegetablesServer.findByVe(vegetables);
        PageInfo<Vegetables> vegetablesInfo = new PageInfo<>(byVe);

        Map<String, Object> res = new HashMap<>();
        if (byVe != null) {
            res.put("code", "200");
            res.put("msg", "查询成功");
            res.put("data", vegetablesInfo);
        } else {
            res.put("code", "201");
            res.put("msg", "查询失败");
        }
        String s = JSON.toJSONString(res);
        return s;
    }

    @ResponseBody
    @RequestMapping(value = "/deleteById/{id}")
    public String deleteById(@PathVariable("id") Integer id) {
        Integer count = vegetablesServer.deleteById(id);
        Map<String, Object> res = new HashMap<>();
        if (count > 0) {
            res.put("code", "200");
            res.put("msg", "删除成功");
        } else {
            res.put("code", "201");
            res.put("msg", "删除失败");
        }
        String s = JSON.toJSONString(res);
        return s;
    }

    @RequestMapping(value = "/update", method = RequestMethod.POST)
    public String update(Vegetables vegetables, HttpSession session, HttpServletRequest request, @RequestParam("sAddressPhoto") MultipartFile file) throws IOException {
//        if (file.getSize() > 0) {
//            // web下文件图片存放位置
//            String concat = "static\\picture\\vegetablesPicture";
//            // 项目文件存放位置（不能实时刷新）
//            String uploadPath1 = "E:\\ideaProjects\\milk\\src\\main\\webapp\\";
////            String uploadPath = Paths.get(System.getProperty("user.dir")).toString() +"\\src\\main\\webapp\\static\\picture\\vegetablesPicture";
//            Path path = Paths.get(uploadPath1 + concat);
//            // 临时存放地址（补充上面实时刷新的缺点）
//            String temporarily = session.getServletContext().getRealPath(concat);
//
//            // 上传文件的名字
//            String uploadFileName = file.getOriginalFilename();
//            // 后缀名
//            String hzm = uploadFileName.substring(uploadFileName.lastIndexOf("."));
//            // 上传文件名字
//            String fileName = System.currentTimeMillis() + hzm;
//
//            /**
//             * 获取文件路径，判断是否存在该文件夹。不存在则创建
//             */
//            File upload = new File(uploadPath1);
//            File uploada = new File(temporarily);
//            if (!upload.isDirectory()) {
//                upload.mkdirs();
//            }
//            if (!uploada.isDirectory()) {
//                uploada.mkdirs();
//            }
//
////            FileDeleteStrategy fileDeleteStrategy = new FileDeleteStrategy();
////            fileDeleteStrategy.delete();
//            // 将图片存入项目文件夹中
//            FileCopyUtils.copy(file.getInputStream(), new FileOutputStream(uploadPath1 + File.separator + fileName));
//            // 将图片存入临时包文件夹中
////            FileCopyUtils.copy(file.getInputStream(), new FileOutputStream(temporarily + File.separator + fileName));
//            FileCopyUtils.copy(file.getInputStream(), new FileOutputStream("E:\\aaa\\" + fileName));
////
//            // 拼接前后段组成前端src能够使用地址存入数据库
//            vegetables.setAddressPhoto(request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + File.separator + concat + File.separator + fileName);
//
        if (file.getSize() > 0) {
            // web下文件图片存放位置
            String concat = "target\\milk-1.0-SNAPSHOT\\static\\picture\\vegetablesPicture";
            String concat2 = "src\\main\\webapp\\static\\picture\\vegetablesPicture";
            // 项目文件存放位置（不能实时刷新）
            String uploadPath = "E:\\ideaProjects\\milk\\" + concat2;
            String uploadPath1 = "E:\\ideaProjects\\milk\\" + concat;
            // 临时存放地址（补充上面实时刷新的缺点）
            String temporarily = session.getServletContext().getRealPath(concat2);
            // 上传文件的名字
            String uploadFileName = file.getOriginalFilename();
            // 后缀名
            String hzm = uploadFileName.substring(uploadFileName.lastIndexOf("."));
            // 上传文件名字
            String fileName = System.currentTimeMillis() + hzm;
            /**
             * 获取文件路径，判断是否存在该文件夹。不存在则创建
             */
            File upload = new File(uploadPath);
            if (!upload.isDirectory()) {
                upload.mkdirs();
            }
            // 将图片存入项目文件夹中
            FileCopyUtils.copy(file.getInputStream(), new FileOutputStream(uploadPath + File.separator + fileName));

            FileCopyUtils.copy(file.getInputStream(), new FileOutputStream(uploadPath1 + File.separator + fileName));

            vegetables.setAddressPhoto(request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + File.separator + concat + File.separator + fileName);
        }

        // 操作数据库
        vegetablesServer.update(vegetables);
        return "vegetables/vegetableslist";
    }

    @RequestMapping(value = "/add", method = RequestMethod.POST)
    public String add(Vegetables vegetables, HttpSession session, @RequestParam("sAddressPhoto") MultipartFile file) throws IOException {
        if (file.getSize() > 0) {
            String concat = "vegetablesPicture";
            String uploadPath = session.getServletContext().getRealPath(concat);

            // 上传文件的名字
            String uploadFileName = file.getOriginalFilename();
            // 后缀名
            String hzm = uploadFileName.substring(uploadFileName.lastIndexOf("."));
            // 上传文件名字
            String fileName = System.currentTimeMillis() + hzm;

            FileCopyUtils.copy(file.getInputStream(), new FileOutputStream(uploadPath + File.separator + fileName));

            vegetables.setAddressPhoto(File.separator + concat + File.separator + fileName);
        }
        vegetablesServer.addVegetables(vegetables);
        return "vegetables/vegetableslist";
    }

}
